package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.*;
import cn.com.hhrcw.mapstruct.EnInfoAdminConvert;
import cn.com.hhrcw.params.EnInfoAdminParams;
import cn.com.hhrcw.service.*;
import cn.com.hhrcw.sms.service.ISysSmsTemplateService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.EnInfoAdminVO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.enums.Roles;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 企业会员管理
 *
 * @author gaoruiyi
 * @since 2020-11-02
 */
@RestController
@Slf4j
@RequestMapping("/admin/enInfo")
@Api(tags = "公司信息表")
@Validated
public class EnInfoAdminController extends JeecgController<EnInfo, IEnInfoService> {

    @Autowired
    private IEnInfoService enInfoService;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private IOpJobService opJobService;

    @Autowired
    private IOpInterviewHistoryService opInterviewHistoryService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IOpDeliveryHistoryService opDeliveryHistoryService;

    @Autowired
    private EnInfoAdminConvert enInfoAdminConvert;

    @Autowired
    private ISysUserDepartService sysUserDepartService;

    @Autowired
    private MySysUserRoleService sysUserRoleService;

    @Autowired
    private ISysSmsTemplateService smsTemplateService;

    /**
     * 企业列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/no_page_list")
    @ApiOperation(value = "无分页列表查询", notes = "无分页列表查询")
    public Result<List<EnInfoAdminVO>> noPageList(EnInfoAdminParams params, HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<EnInfo> queryWrapper = QueryGenerator.initQueryWrapper(new EnInfo(), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        //state 0：审核成功
        queryWrapper.eq("state", 0);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        //企业名称
        if (StrUtil.isNotBlank(params.getEnName())) {
            queryWrapper.like("en_name", params.getEnName());
        }
        //企业名称
        if (StrUtil.isNotBlank(params.getEnTrade())) {
            queryWrapper.like("en_trade", params.getEnTrade());
        }
        //判断前端是否传入专场id
        if(StringUtils.isNotBlank(params.getSsSessionId())){
            //判断前端是否传入专场id
            queryWrapper.lambda().inSql(EnInfo::getId,
                    "SELECT distinct company_id FROM op_job WHERE bs_id IN("+params.getSsSessionId()+") and del_flag = 0");
        }
        if(StringUtils.isNotBlank(sysUser.getAdminDivision())){
            //省级用户
            if(sysUser.getAdminDivision().endsWith("0000")){
                queryWrapper.eq("province", sysUser.getAdminDivision());
            }else{
                if("410100".equals(sysUser.getAdminDivision())){
                    //郑州市
                    queryWrapper.eq("city", sysUser.getAdminDivision());
                    queryWrapper.ne("en_address", "410000,410100,410173");
                }else if("410173".equals(sysUser.getAdminDivision())){
                    //航空港区
                    queryWrapper.eq("en_address", "410000,410100,410173");
                }else{
                    //其他
                    queryWrapper.eq("city", sysUser.getAdminDivision());
                }
            }
            //增加企业类型查询  所属单位  gxt  工信厅
            queryWrapper.eq("aff_unit", "gxt");
            //enInfoQueryWrapper = queryWrapper.lambda();
            ////判断前端是否传入专场id
            //if(StringUtils.isNotBlank(params.getSsSessionId())){
            //    enInfoQueryWrapper.inSql(EnInfo::getId, "SELECT company_id FROM op_job WHERE bs_id IN("+params.getSsSessionId()+") GROUP BY company_id");
            //}else{
            //    List<DictModel> models = sysBaseApi.queryDictItemsByCode("gxt_ss_session");
            //    if(models.size()>0){
            //        String result = "";
            //        for (DictModel dictModel : models){
            //            result += "'"+dictModel.getValue() + "',";
            //        }
            //        String reSql = result.substring(0, result.length() - 1);
            //        enInfoQueryWrapper.inSql(EnInfo::getId, "SELECT company_id FROM op_job WHERE bs_id IN("+reSql+") GROUP BY company_id");
            //    }else{
            //        //为空时，不让查数据
            //        enInfoQueryWrapper.inSql(EnInfo::getId, "null");
            //    }
            //}
        }
        List<EnInfo> list = enInfoService.list(queryWrapper);
        if(StringUtils.isNotBlank(sysUser.getAdminDivision()) && CollUtil.isNotEmpty(list)){
            for (EnInfo enInfo:list) {
                Integer count = 0;
                QueryWrapper<OpJob> opJobWrapper = QueryGenerator.initQueryWrapper(new OpJob(), request.getParameterMap());
                if(StringUtils.isNotBlank(params.getSsSessionId())){
                    opJobWrapper.eq("company_id",enInfo.getId()).eq("bs_id",params.getSsSessionId()).eq("del_flag", false);
                    count = opJobService.count(opJobWrapper);
                }else{
                    List<DictModel> models = sysBaseApi.queryDictItemsByCode("gxt_ss_session");
                    if(CollUtil.isNotEmpty(models)){
                        opJobWrapper.eq("company_id",enInfo.getId()).in("bs_id",models.stream().map(DictModel::getValue).toArray()).eq("del_flag", false);
                        count = opJobService.count(opJobWrapper);
                    }
                }
                enInfo.setPostNum(count);
            }
        }
        enInfoAdminConvert.toVO(list);
        return Result.ok(enInfoAdminConvert.toVO(list));
    }

    /**
     * 企业会员列表
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog(value = "企业会员列表", logType = 2, ty = "visit")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<EnInfoAdminVO>> list(EnInfoAdminParams params, HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<EnInfo> queryWrapper = QueryGenerator.initQueryWrapper(new EnInfo(), request.getParameterMap());
        queryWrapper.eq("del_flag", false);
        if (StringUtils.isBlank(params.getField())) {
            queryWrapper.orderByDesc("create_time");
        } else {
            queryWrapper.orderBy(true, params.getSort(), toUnderlineName(params.getField()));
        }
        //企业名称
        if (StrUtil.isNotBlank(params.getEnName())) {
            queryWrapper.like("en_name", params.getEnName());
        }

        //企业名称
        if (StrUtil.isNotBlank(params.getEnTrade())) {
            queryWrapper.like("en_trade", params.getEnTrade());
        }
        //企业省份
        if (StrUtil.isNotBlank(params.getEnAddress())) {
            queryWrapper.eq("en_address", params.getEnAddress());
        }
        //企业性质
        if (StrUtil.isNotBlank(params.getEnNature())) {
            queryWrapper.eq("en_nature", params.getEnNature());
        }
        //是否自主注册
        if (params.getActFlag() != null) {
            queryWrapper.eq("act_flag", params.getActFlag());
        }
        //审核状态0审核成功1未审核
        if (params.getState() != null) {
            queryWrapper.eq("state", params.getState());
        }
        //在招职位数
        if (StrUtil.isNotBlank(params.getPostNum())) {
            String[] num = params.getPostNum().split(",");
            queryWrapper.le("post_num", num[1]).ge("post_num", num[0]);
        }
        //简历投递量
        if (StrUtil.isNotBlank(params.getDeliverNum())) {
            String[] num = params.getDeliverNum().split(",");
            queryWrapper.le("deliver_num", num[1]).ge("deliver_num", num[0]);
        }
        //反馈率
        if (StrUtil.isNotBlank(params.getFeedAck())) {
            String[] num = params.getFeedAck().split(",");
            queryWrapper.between("feed_ack", num[0], num[1]);
        }
        //面试率
        if (StrUtil.isNotBlank(params.getInterviewRate())) {
            String[] num = params.getInterviewRate().split(",");
            queryWrapper.between("interview_rate", num[0], num[1]);
        }
        //入职率
        if (StrUtil.isNotBlank(params.getInductionRate())) {
            String[] num = params.getInductionRate().split(",");
            queryWrapper.between("induction_rate", num[0], num[1]);
        }
        //判断前端是否传入专场id
        if(StringUtils.isNotBlank(params.getSsSessionId())){
            //判断前端是否传入专场id
            queryWrapper.lambda().inSql(EnInfo::getId,
                    "SELECT distinct company_id FROM op_job WHERE bs_id IN("+params.getSsSessionId()+") and del_flag = 0");
        }
        if(StringUtils.isNotBlank(sysUser.getAdminDivision())){
            //省级用户
            if(sysUser.getAdminDivision().endsWith("0000")){
                queryWrapper.eq("province", sysUser.getAdminDivision());
            }else{
                if("410100".equals(sysUser.getAdminDivision())){
                    //郑州市
                    queryWrapper.eq("city", sysUser.getAdminDivision());
                    queryWrapper.ne("en_address", "410000,410100,410173");
                }else if("410173".equals(sysUser.getAdminDivision())){
                    //航空港区
                    queryWrapper.eq("en_address", "410000,410100,410173");
                }else{
                    //其他
                    queryWrapper.eq("city", sysUser.getAdminDivision());
                }
            }
            //增加企业类型查询  企业类型  gxt  工信厅
            queryWrapper.eq("aff_unit", "gxt");
            //enInfoQueryWrapper = queryWrapper.lambda();
            ////判断前端是否传入专场id
            //if(StringUtils.isNotBlank(params.getSsSessionId())){
            //    enInfoQueryWrapper.inSql(EnInfo::getId, "SELECT company_id FROM op_job WHERE bs_id IN("+params.getSsSessionId()+") GROUP BY company_id");
            //}else{
            //    List<DictModel> models = sysBaseApi.queryDictItemsByCode("gxt_ss_session");
            //    if(CollUtil.isNotEmpty(models)){
            //        String result = "";
            //        for (DictModel dictModel : models){
            //            result += "'"+dictModel.getValue() + "',";
            //        }
            //        String reSql = result.substring(0, result.length() - 1);
            //        enInfoQueryWrapper.inSql(EnInfo::getId, "SELECT company_id FROM op_job WHERE bs_id IN("+reSql+") GROUP BY company_id");
            //    }else{
            //        //为空时，不让查数据
            //        enInfoQueryWrapper.eq(EnInfo::getId, "");
            //    }
            //}
        }
        IPage<EnInfo> page = enInfoService.page(params.page(), queryWrapper);
        List<EnInfo> enInfoList = page.getRecords();
        if(StringUtils.isNotBlank(sysUser.getAdminDivision())&& CollUtil.isNotEmpty(enInfoList)){
            for (EnInfo enInfo:enInfoList) {
                Integer count = 0;
                QueryWrapper<OpJob> opJobWrapper = QueryGenerator.initQueryWrapper(new OpJob(), request.getParameterMap());
                if(StringUtils.isNotBlank(params.getSsSessionId())){
                    opJobWrapper.eq("company_id",enInfo.getId()).eq("bs_id",params.getSsSessionId()).eq("del_flag", false);
                     count = opJobService.count(opJobWrapper);
                }else{
                    List<DictModel> models = sysBaseApi.queryDictItemsByCode("gxt_ss_session");
                    if(CollUtil.isNotEmpty(models)){
                        opJobWrapper.eq("company_id",enInfo.getId()).in("bs_id",models.stream().map(DictModel::getValue).toArray()).eq("del_flag", false);
                        count = opJobService.count(opJobWrapper);
                    }
                }
                enInfo.setPostNum(count);
            }
            page.setRecords(enInfoList);
        }
        return Result.ok((Page) page.convert(enInfoAdminConvert::toVO));
    }
    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "企业会员根据id查看", notes = "企业会员根据id查看")
    @AutoLog(value = "企业会员详细信息", logType = 2, ty = "visit")
    public Result<EnInfoAdminVO> queryById(String id) {
        EnInfo enInfo = enInfoService.lambdaQuery().eq(EnInfo::getId, id).eq(EnInfo::getDelFlag, false).one();
        if (enInfo == null) {
            throw new JeecgBootException("数据不存在");
        }
        List<SysUserDepart> departs = sysUserDepartService.lambdaQuery().eq(SysUserDepart::getDepId, enInfo.getId()).list();
        //今日发布职位
        Integer dayPublishCount = opJobService.lambdaQuery().eq(OpJob::getDelFlag, false).eq(OpJob::getCompanyId, enInfo.getId()).ge(OpJob::getCreateTime, DateUtil.beginOfDay(DateUtil.date())).le(OpJob::getCreateTime, DateUtil.endOfDay(DateUtil.date())).count();
        //本月发布职位
        Integer monthPublishCount = opJobService.lambdaQuery().eq(OpJob::getDelFlag, false).eq(OpJob::getCompanyId, enInfo.getId()).ge(OpJob::getCreateTime, DateUtil.beginOfMonth(DateUtil.date())).le(OpJob::getCreateTime, DateUtil.endOfMonth(DateUtil.date())).count();
        //年度发布职位
        Integer yearPublishCount = opJobService.lambdaQuery().eq(OpJob::getDelFlag, false).eq(OpJob::getCompanyId, enInfo.getId()).ge(OpJob::getCreateTime, DateUtil.beginOfYear(DateUtil.date())).le(OpJob::getCreateTime, DateUtil.endOfYear(DateUtil.date())).count();
        EnInfoAdminVO vo = enInfoAdminConvert.toVO(enInfo);
        vo.setAffUnit(enInfo.getAffUnit());
        if (CollUtil.isNotEmpty(departs)) {
            PiInfo piInfo = piInfoService.lambdaQuery().in(PiInfo::getUserId, departs.stream().map(SysUserDepart::getUserId).toArray()).eq(PiInfo::getEnRoleType, 1).eq(PiInfo::getDelFlag, false).one();
            if (piInfo != null) {
                vo.setName(piInfo.getName());
                vo.setCallName(piInfo.getNickName());
                vo.setMobile(piInfo.getPhone());
                vo.setEnMail(piInfo.getEmail());
                //添加email显示
                vo.setIdNumber(piInfo.getIdNumber());
                vo.setPositiveFileid(piInfo.getPositiveFileid());
                vo.setBackFileid(piInfo.getBackFileid());
            }
            vo.setDayPublishCount(dayPublishCount);
            vo.setMonthPublishCount(monthPublishCount);
            vo.setYearPublishCount(yearPublishCount);

            //面试邀请
            List<OpInterviewHistory> list = opInterviewHistoryService.lambdaQuery().eq(OpInterviewHistory::getDelFlag, false).eq(OpInterviewHistory::getCompanyId, enInfo.getId()).list();
            int interview = list.size();
            if (interview == 0) {
                vo.setInterviewRate(BigDecimal.ZERO);
            } else {
                //接受面试邀请数量
                long accept = list.stream().filter(e -> e.getOutLineState() == 1).count();
                //面试率
                double interviewRate = NumberUtil.div(accept, interview) * 100;
                vo.setInterviewRate(NumberUtil.round(interviewRate, 2));
            }
            //投递数据
            List<OpDeliveryHistory> deliveryHistories = opDeliveryHistoryService.lambdaQuery().eq(OpDeliveryHistory::getDelFlag, false).eq(OpDeliveryHistory::getCompanyId, enInfo.getId()).list();
            int deliveryCount = deliveryHistories.size();
            if (deliveryCount == 0) {
                vo.setFeedAck(BigDecimal.ZERO);
                vo.setInductionRate(BigDecimal.ZERO);
            } else {
                long feedback = deliveryHistories.stream().filter(e -> e.getState() >= 1 && e.getScreenFlag()).count();
                //反馈率
                double feedAck = NumberUtil.div(feedback, deliveryCount) * 100;
                vo.setFeedAck(NumberUtil.round(feedAck, 2));
                //入职率
                long inductionCount = deliveryHistories.stream().filter(e -> e.getState() == 6).count();
                long inductionTotal = deliveryHistories.stream().filter(e -> ArrayUtil.contains(new int[]{5, 6, 8}, e.getState())).count();
                if (inductionTotal > 0) {
                    BigDecimal inductionRate = Convert.toBigDecimal(NumberUtil.div(inductionCount, inductionTotal, 2) * 100);
                    vo.setInductionRate(inductionRate);
                }
            }
        }
        return Result.ok(vo);
    }

    /**
     * 添加
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog(logType = 2, ty = "insert", value = "添加企业会员")
    @ApiOperation(value = "企业会员添加", notes = "企业会员添加")
    @RequiresPermissions("enInfo:add")
    public Result<?> add(@RequestBody @Valid EnInfoAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysUser user = sysUserService.lambdaQuery().eq(SysUser::getPhone, params.getMobile() + "@ent").one();
        Assert.isNull(user, "手机号已注册");


        int count = enInfoService.lambdaQuery().eq(EnInfo::getEnName, params.getEnName()).eq(EnInfo::getDelFlag, false).count();
        Assert.isFalse(count > 0, "企业名称已存在");
        /**
         * 保存后为企业生成一个账号，默认密码6个0；未完成
         * TODO 账号创建后需要将账号密码通过邮件发送
         */
        //创建登录用户
        user = new SysUser();
        String username = StrUtil.format("{}@ent", Long.toString(Convert.toLong(params.getMobile()), 32));
        String phone = StrUtil.format("{}@ent", params.getMobile());
        user.setUsername(username);
        String salt = oConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(username, salt, salt);
        user.setSalt(salt);
        user.setRealname(username);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(false);
        user.setActivitiSync(false);
        user.setEmail(params.getEmail());
        user.setPhone(phone);
        //创建用户信息
        PiInfo piInfo = new PiInfo();
        piInfo.setName(params.getName());
        piInfo.setUsername(sysUser.getUsername());
        piInfo.setPhone(phone);
        piInfo.setUserId(user.getId());
        piInfo.setEnRoleType(1);
        piInfo.setRoleType("1,");

        piInfo.setEmail(params.getEmail());
        piInfo.setIdNumber(params.getIdNumber());
        piInfo.setPositiveFileid(params.getPositiveFileid());
        piInfo.setBackFileid(params.getBackFileid());
        piInfo.setNickName(params.getCallName());
        piInfo.setDelFlag(false);
        //创建企业
        EnInfo enInfo = enInfoAdminConvert.toEntity(params);
        enInfo.setCreateBy(sysUser.getId());
        enInfo.setCreateTime(DateUtil.date());
        enInfo.setState(0);
        enInfo.setActFlag(false);
        enInfo.setDelFlag(false);
        enInfo.setPostNum(0);
        enInfo.setDeliverNum(0);
        if(StringUtils.isNotBlank(sysUser.getAdminDivision())){
            //所属单位
            enInfo.setAffUnit("gxt");
        }
        boolean created = this.enInfoService.createCompany(user, piInfo, enInfo);
        sysUserDepartService.referenceUser(user.getId(), enInfo.getId());
        sysBaseApi.addRole(user.getId(), Roles.ENT);
        return created ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 禁用/启用
     *
     * @param id 企业用户id
     * @return
     */
    @GetMapping("/enableOrDisable")
    @AutoLog(logType = 2, ty = "update", value = "禁用/启用企业会员")
    @RequiresPermissions("enInfo:disable")
    public Result enableOrDisable(String id) {
        EnInfo enInfo = this.enInfoService.getById(id);
        enInfo.setEnabled(!enInfo.getEnabled());
        boolean updated = this.enInfoService.updateById(enInfo);
        return updated ? Result.ok() : Result.error("操作失败");
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(logType = 2, ty = "update", value = "企业会员编辑")
    @ApiOperation(value = "企业会员编辑", notes = "企业会员编辑")
    @RequiresPermissions("enInfo:edit")
    public Result<?> edit(@RequestBody @Valid EnInfoAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Integer count = enInfoService.lambdaQuery().ne(EnInfo::getId, params.getId()).eq(EnInfo::getEnName, params.getEnName()).eq(EnInfo::getDelFlag, false).count();
        Assert.isFalse(count > 0, "企业名称已存在");
        List<SysUserDepart> list = this.sysUserDepartService.lambdaQuery().eq(SysUserDepart::getDepId, params.getId()).list();
        PiInfo old = this.piInfoService.lambdaQuery().in(PiInfo::getUserId, list.stream().map(SysUserDepart::getUserId).toArray()).eq(PiInfo::getEnRoleType, 1).one();
        //判断新旧手机号是否为同一用户
        PiInfo fresh = this.piInfoService.lambdaQuery().ne(PiInfo::getId, old.getId()).eq(PiInfo::getPhone, params.getMobile() + "@ent").eq(PiInfo::getDelFlag, false).one();
        Assert.isNull(fresh, "手机号已绑定企业,请先解绑");
        fresh = old;
        String mobile = params.getMobile() + "@ent";
        String username = Long.toString(Convert.toLong(params.getMobile()), 32) + "@ent";
        boolean logout = !StrUtil.equals(mobile, old.getPhone());
        EnInfo enInfo = enInfoAdminConvert.toEntity(params);
        enInfo.setAffUnit(params.getAffUnit());
        enInfoService.updateById(enInfo);
        this.piInfoService.lambdaUpdate().eq(PiInfo::getUserId, list.stream().map(SysUserDepart::getUserId).toArray()).set(PiInfo::getEnRoleType, 0).update();
        fresh.setUsername(username);
        fresh.setEmail(params.getEmail());
        fresh.setName(params.getName());
        fresh.setIdNumber(params.getIdNumber());
        fresh.setPositiveFileid(params.getPositiveFileid());
        fresh.setBackFileid(params.getBackFileid());
        fresh.setNickName(params.getCallName());
        fresh.setEnRoleType(1);
        fresh.setPhone(mobile);
        piInfoService.updateById(fresh);


        this.sysUserService.lambdaUpdate().eq(SysUser::getId, fresh.getUserId())
            .set(SysUser::getEmail, params.getEmail()).update();
        //2020年12月31日15:33:14 添加email同步修改

        //退出登陆
        if (logout) {
            //修改手机号
            this.sysUserService.lambdaUpdate().eq(SysUser::getId, fresh.getUserId())
                .set(SysUser::getUsername, username)
                .set(SysUser::getPhone, params.getMobile() + "@ent").update();
            String token = Convert.toStr(redisUtil.get("ONLINE_" + fresh.getUserId()));
            //清空用户登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
            //清空用户登录Shiro权限缓存
            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + sysUser.getId());
            //清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
            redisUtil.del(String.format("%s::%s", CacheConstant.SYS_USERS_CACHE, sysUser.getUsername()));
            redisUtil.del("ONLINE_" + sysUser.getId());
        }
        return Result.ok();
    }

    /**
     * 企业会员审核
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/enExamine")
    @AutoLog(logType = 2, ty = "update", value = "企业会员审核")
    @ApiOperation(value = "企业会员审核", notes = "企业会员审核")
    @RequiresPermissions("enInfo:edit")
    public Result<?> enExamine(@RequestBody EnInfoAdminParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        EnInfo one = enInfoService.lambdaQuery().eq(EnInfo::getId, params.getId()).one();
        one.setState(params.getState());
        one.setRemark(params.getRemark());
        boolean enUpdated = this.enInfoService.updateById(one);
        //授予企业用户角色权限
        List<SysUserDepart> departs = this.sysUserDepartService.lambdaQuery().eq(SysUserDepart::getDepId, params.getId()).list();
        PiInfo piInfo = this.piInfoService.lambdaQuery().in(PiInfo::getUserId, departs.stream().map(SysUserDepart::getUserId).toArray()).eq(PiInfo::getEnRoleType, 1).one();
        Dict dict = Dict.create().set("name", piInfo.getName()).set("enName", one.getEnName()).set("phone", piInfo.getPhone().split("@")[0]).set("remark", one.getRemark());

        if (one.getState() == 0) {
            departs.forEach(e -> sysBaseApi.addRole(e.getUserId(), Roles.ENT));
            String text = smsTemplateService.sendNews("en_pass_msg", dict);
            smsTemplateService.sendSms(new String[]{piInfo.getPhone()}, text);
            //审核公司用户登录token
            String online = "ONLINE_";
            if (redisUtil.hasKey(online + piInfo.getUserId())) {
                String token = (String) redisUtil.get("ONLINE_" + piInfo.getUserId());
                redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
            }
            //清空用户登录Shiro权限缓存
            redisUtil.del(CommonConstant.PREFIX_USER_SHIRO_CACHE + piInfo.getUserId());
        } else {
            String text = smsTemplateService.sendNews("en_no_pass_msg", dict);
            smsTemplateService.sendSms(new String[]{piInfo.getPhone()}, text);
        }
        return enUpdated ? Result.ok() : Result.error("审核失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(logType = 2, ty = "delete", value = "企业会员删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("enInfo:delete")
    public Result delete(@NotEmpty(message = "id必传") String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        this.enInfoService.deleteCompany(id);
        return Result.ok();
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, EnInfoAdminParams params) {
        EnInfo enInfo = enInfoAdminConvert.toEntity(params);
        enInfo.setDelFlag(false);
        QueryWrapper<EnInfo> queryWrapper = QueryGenerator.initQueryWrapper(enInfo, request.getParameterMap());
        List<EnInfo> data = enInfoService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("公司信息表", "公司信息表");
        String url = super.exportXls(exportParams, EnInfoAdminVO.class, enInfoAdminConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, EnInfo.class);
    }

}
